package com.lh.music.activity;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lh.music.PlayApplication;
import com.lh.music.R;
import com.lh.music.constant.Constants;
import com.lh.music.service.PlayNetService;
import com.lh.music.service.PlayService;

import java.util.Timer;
import java.util.TimerTask;

public  class BaseActivity extends AppCompatActivity implements View.OnClickListener{
    protected PlayApplication app;
    private WindowManager windowManager;
    //根视野
    private FrameLayout mContentContainer;
    //浮动视野
     View mFloatView;
    //播放栏中的控件
    TextView song_name;
    TextView artist_name;
    ImageView artist_icon;
    ImageView controllPlay;
    ImageView nextPlay;
    ImageView listPlay;
    ProgressBar songProgress;
    Timer timer;
    PlayConnection playConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getChildContentView());
        app= (PlayApplication) getApplication();
        //初始化通知栏
        initNotification();
        //添加播放栏
        addFloatView();
        //找到播放栏中的各个控件
        findViewByIdFromMusicView();
        //绑定本地音乐的服务  服务只绑定一次
        if (app.music==null){
            //绑定服务
            initService();
        }
        //绑定网络音乐的服务  服务只绑定一次
        if (app.netMusic==null){
            //绑定服务
            initNetService();
        }





    }

    private void initNetService() {
        Intent broadIntent=new Intent(this, PlayNetService.class);
        playConnection=new PlayConnection();
        startService(broadIntent);
        bindService(broadIntent,playConnection,BIND_AUTO_CREATE);
    }

    private void initService() {
        Intent broadIntent=new Intent(this, PlayService.class);
        playConnection=new PlayConnection();
        startService(broadIntent);
        bindService(broadIntent,playConnection,BIND_AUTO_CREATE);
        //sendBroadcast(broadIntent);
    }

    private void addFloatView() {
        ViewGroup mDecorView = (ViewGroup) getWindow().getDecorView();
        mContentContainer = (FrameLayout) ((ViewGroup) mDecorView.getChildAt(0)).getChildAt(1);
        mFloatView =  LayoutInflater.from(getBaseContext()).inflate(R.layout.float_music_control_layout, null);
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.BOTTOM;
        mContentContainer.addView(mFloatView,layoutParams);
    }

    @Override
    protected void onStart() {
        super.onStart();
        updateMusicView();
        //定时更新UI
        timerUpdateMusicView();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (timer!=null){
            timer.cancel();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onPostCreate(savedInstanceState, persistentState);

    }
    @Override
    public void startActivity(Intent intent){
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);//设置切换没有动画，用来实现活动之间的无缝切换
        super.startActivity(intent);
    }

    //获得子布局，向父控件注入布局
    public View getChildContentView(){
        View view=new View(this);
        return  view;
    }
    //找到播放栏中的各个控件,并且初始化
    public void findViewByIdFromMusicView(){
        song_name= (TextView) mFloatView.findViewById(R.id.song_name);
        song_name.setFocusable(true);
        artist_name= (TextView) mFloatView.findViewById(R.id.artist_name);
        artist_icon= (ImageView) mFloatView.findViewById(R.id.artist_icon);
        controllPlay= (ImageView) mFloatView.findViewById(R.id.controll_play);
         nextPlay= (ImageView) mFloatView.findViewById(R.id.next_play);
        listPlay= (ImageView) mFloatView.findViewById(R.id.list_play);
        songProgress= (ProgressBar) mFloatView.findViewById(R.id.progress);
        //给播放栏中的控件绑定单击事件
        controllPlay.setOnClickListener(this);
        nextPlay.setOnClickListener(this);
        listPlay.setOnClickListener(this);
        mFloatView.findViewById(R.id.linearLayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(BaseActivity.this,PlayActivity.class);
                startActivity(intent);
            }
        });
        updateMusicView();


    }
    protected Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what==1){
                if(app.music!=null){
                    app.currentProgress=app.music.getSongProgress();
                }
                updateMusicView();
            }
        }
    };

    protected void timerUpdateMusicView() {
        timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg=handler.obtainMessage();
                msg.what=1;
              /* if (app.music!=null){

                }*/
                handler.sendMessage(msg);
            }
        },0,400);
    }

    @Override
    public void onClick(View v) {
        Intent broadIntent=new Intent();
        switch (v.getId()){
            //控制播放按钮的功能
            case R.id.controll_play:
                //播放本地音乐的功发送的广播
                if (app.currentType==Constants.LOCAL){
                    if (app.songState==Constants.PLAYING){
                        //发送一个暂停播放的广播
                        Toast.makeText(app, "pause", Toast.LENGTH_SHORT).show();
                        broadIntent.setAction(Constants.PAUSE_ACTION);
                        sendBroadcast(broadIntent);
                        //app.songState=Constants.PAUSED;
                        updateMusicView();
                    }else if (app.songState==Constants.PAUSED){
                        //发送一个继续播放的广播
                        Toast.makeText(app, "continue", Toast.LENGTH_SHORT).show();
                        broadIntent.setAction(Constants.CONTINUE_ACTION);
                        sendBroadcast(broadIntent);
                        //app.songState=Constants.PLAYING;
                        updateMusicView();
                    }else{
                        //发送一个开始播放的广播
                        broadIntent.setAction(Constants.PLAY_ACTION);
                        //加载上次播放的列表
                        broadIntent.putExtra("init","init");
                        sendBroadcast(broadIntent);
                        //app.songState=Constants.PLAYING;
                        //updateMusicView();
                        Toast.makeText(app, "初始化音乐，开始播放", Toast.LENGTH_SHORT).show();

                    }
                }//播放的是网络音乐发送的广播
                else {
                    if (app.songState==Constants.PLAYING){
                        //发送一个暂停播放的广播
                        Toast.makeText(app, "pause", Toast.LENGTH_SHORT).show();
                        broadIntent.setAction(Constants.NET_PAUSE_ACTION);
                        sendBroadcast(broadIntent);
                        //updateMusicView();
                    }else if (app.songState==Constants.PAUSED){
                        //发送一个继续播放的广播
                        Toast.makeText(app, "continue", Toast.LENGTH_SHORT).show();
                        broadIntent.setAction(Constants.NET_CONTINUE_ACTION);
                        sendBroadcast(broadIntent);
                        updateMusicView();
                    }
                }

                break;
            //下一首按钮的功能
            case R.id.next_play:
                //类型为本地音乐
                if (app.currentType==Constants.LOCAL){
                    if (app.songState==Constants.STOPED){
                        broadIntent.setAction(Constants.PLAY_ACTION);
                        //加载上次播放的列表
                        broadIntent.putExtra("init","init");
                        sendBroadcast(broadIntent);
                        Toast.makeText(app, "初始化音乐，开始播放", Toast.LENGTH_SHORT).show();
                    }else{
                        //发送下一曲的广播
                        broadIntent.setAction(Constants.NEXT_ACTION);
                        sendBroadcast(broadIntent);
                    }
                }//类型为网络音乐
                else {
                    //发送下一曲的广播
                    broadIntent.setAction(Constants.NET_NEXT_ACTION);
                    sendBroadcast(broadIntent);
                }

                break;
        }
    }
    //更新播放栏中控件的状态
    protected void updateMusicView(){
        //播放的是本地音乐
        if (app.currentType==Constants.LOCAL){
            if (app.currentSong!=null){
                song_name.setText(app.currentSong.getTitle());
                artist_name.setText(app.currentSong.getArtist());
                songProgress.setMax(app.currentDuration);
                songProgress.setProgress(app.currentProgress);
                artist_icon.setImageResource(R.mipmap.a9d);
            }
        }else{
            if (app.currentNetSong!=null){
                //排行榜
                if (app.currentNetSong.getSong_id()!=null){
                    song_name.setText(app.currentNetSong.getTitle());
                    artist_name.setText(app.currentNetSong.getAuthor());
                    songProgress.setMax(app.currentDuration);
                    songProgress.setProgress(app.currentProgress);
                    Glide.with(this)
                            .load(app.currentNetSong.getPic_big())
                            .placeholder(R.mipmap.a9d)
                            .crossFade()
                            .centerCrop()
                            .into(artist_icon);
                }//电台
                if (app.currentNetSong.getSongid()!=null){
                    song_name.setText(app.currentNetSong.getTitle());
                    artist_name.setText(app.currentNetSong.getArtist());
                    songProgress.setMax(app.currentDuration);
                    songProgress.setProgress(app.currentProgress);
                    Glide.with(this)
                            .load(app.currentNetSong.getThumb())
                            .placeholder(R.mipmap.a9d)
                            .crossFade()
                            .centerCrop()
                            .into(artist_icon);
                }

            }
        }

        switch (app.songState){
            case Constants.PAUSED:
                controllPlay.setImageResource(R.mipmap.playbar_btn_play);
                break;
            case Constants.PLAYING:
                controllPlay.setImageResource(R.mipmap.playbar_btn_pause);
                break;
        }
    }
    class PlayConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }
    private void initNotification() {
        RemoteViews remoteViews=new RemoteViews(getPackageName(),R.layout.notiify_music_layout);
        app.notification=new Notification.Builder(this)
                .setSmallIcon(R.mipmap.a9d)
                .setContent(remoteViews)
                .build();
        //发送上一首
        Intent prevIntent=new Intent(Constants.PREV_ACTION);
        PendingIntent prevPending=PendingIntent.getBroadcast(this,0,prevIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.prev_play,prevPending);
        //发送下一首
        Intent nextIntent=new Intent(Constants.NEXT_ACTION);
        PendingIntent nextPending=PendingIntent.getBroadcast(this,0,nextIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.next_play,nextPending);
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer!=null){
            timer.cancel();
        }
        //unbindService(playConnection);
    }
}
